package com.epro.dx.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import com.epro.dx.R;
import com.epro.dx.adapter.ProductListAdapter;
import com.epro.dx.adapter.SpecialAdapter;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.listenner.OnSortViewItemClickListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshGridView;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.task.GetActiveInfoAsyncTask;
import com.epro.dx.task.GetActivityProductListAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.SortView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.AdPromotionServiceProvider;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.ActiveModel;
import com.weipu.common.facade.model.BannerModel;
import com.weipu.common.facade.model.ModuleChildrenModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.facade.model.SearchModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.StringUtil;

/**
 * 促销商品列表页面
 * 
 * @author hjd008
 * @version [版本号, 2014-12-24]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class SpecialActivity extends BaseFragmentActivity implements OnClickListener, OnSortViewItemClickListenner{
	private PullToRefreshGridView pullToRefreshGridView;

	/**
	 * 商品列表
	 */
	private ArrayList<ProductModel> listProductModel = new ArrayList<ProductModel>();

	/**
	 * 传递对象的类
	 */
	private BannerModel bannerModel;

//	private SpecialAdapter adatper;
	
	private ProductListAdapter adatper;
	
	private AdPromotionServiceProvider adPromotionServiceProvider;

	private SortView sortLayout;

  	private LinearLayout loadingLayout;
  	
  	//返回列表顶部按钮
  	private ImageButton toTop;
  	
  	private int densityDpi;

	private Tracker tracker;

	private RelativeLayout filterModelLayout;

	private int activType;

	private String activID;
	
	private int pageIndex = 0;
	
	private boolean isLoading =false;

	private boolean isFromMessage;

	private boolean needCheckValid;
	
	//活动失效提示页面
	private RelativeLayout invalidActiveLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		tracker = ((DXApplication)getApplication()).getTracker(TrackerName.APP_TRACKER);
		adPromotionServiceProvider = ProviderFactory
				.createAdPromotionServiceProvider();
		setContentView(R.layout.activity_special);
//		bannerModel = (BannerModel) getIntent().getSerializableExtra(
//				"picmodel");
//		if(null==bannerModel){
//			finish();
//			return;
//		}
//		setTitleContent(bannerModel.getBannerName());
		initView();
		getIntentData();
		if(needCheckValid){
			//先校验活动的有效性
			GetActiveInfoAsyncTask getActiveInfoAsyncTask = new GetActiveInfoAsyncTask(3, activID, new MyAsyncTaskListenner() {
				
				@Override
				public void onPreTask() {
					showLoadingLayout(null);
				}
				
				@Override
				public void onPostTask(String result, Object obj) {
					hideAllLayout();
					//判断活动是否有效
					if("0".equals(result) && null!=obj){
						ActiveModel model = (ActiveModel)obj;
						if(model.getState() == ActiveModel.STATE_OFFLINE || model.getState() == ActiveModel.STATE_STOP){
							//活动下线
							sortLayout.setVisibility(View.GONE);
							filterModelLayout.setVisibility(View.GONE);
							invalidActiveLayout.setVisibility(View.VISIBLE);
							return;
						}
					}
					excuteTask(false);
				}
			});
			AsyncTaskUtil.executeTask(getActiveInfoAsyncTask);
		}else{
			excuteTask(false);
		}
	}

	/**
	 * @创建：Tony 2016-4-14下午5:31:45
	 * @描述：获取传过来的数据
	 */
	private void getIntentData() {
		// TODO 
		Intent intent = getIntent();
		if(null!=intent){
			activType = intent.getIntExtra(ModuleChildrenModel.ACTIVTYPE, -1);
			activID = intent.getStringExtra(ModuleChildrenModel.ACTIVID);
			isFromMessage = intent.getBooleanExtra("IsFromMessage", false);
			needCheckValid = intent.getBooleanExtra("needCheckValid", false);
			String bannerName = intent.getStringExtra("BannerName");
			if(!TextUtils.isEmpty(bannerName)){
				setTitleContent(bannerName);
			}
		}
		
		adatper = new ProductListAdapter(SpecialActivity.this,
				listProductModel, false, densityDpi,tracker);
		
		pullToRefreshGridView.setAdapter(adatper);
		
		pullToRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<GridView> refreshView) {
				isLoading = true;
				excuteTask(true);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<GridView> refreshView) {
				isLoading = true;
				++pageIndex;
				excuteTask(false);
			}
		});
		
		retryBtn.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						excuteTask(false);
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		tracker.setScreenName("BannerProductList");
		tracker.send(new HitBuilders.ScreenViewBuilder().setNewSession().build());
	}
	@Override
	protected void onPause() {
		super.onPause();
		tracker.setScreenName(null);
	}
	
	/**
	 * 执行获取数据任务
	 */
	private void excuteTask(final boolean isDown) {
//		AsyncTaskUtil.executeTask(new GetBannerProductListAsyncTask());
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//			new GetBannerProductListAsyncTask()
//					.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//		} else {
//			new GetBannerProductListAsyncTask().execute();
//		}
		AsyncTaskUtil.executeTask(new GetActivityProductListAsyncTask(SpecialActivity.this, activType, activID, pageIndex, Constant.LIST_PAGE_COUNT, 
				sortLayout.getCurrentSortType(), new MyAsyncTaskListenner() {
			
			@Override
			public void onPreTask() {
				// TODO 
				if(!isLoading){
					showLoadingLayout(pullToRefreshGridView);
				}
			}
			
			@Override
			public void onPostTask(String result, Object obj) {
				// TODO
				if(!isFinishing()){
					if(isLoading){
						pullToRefreshGridView.onRefreshComplete();
						isLoading = false;
					}
					hideAllLayout(pullToRefreshGridView);
					
					if("0".equals(result)){
						@SuppressWarnings("unchecked")
						ArrayList<ProductModel> list = (ArrayList<ProductModel>)obj;
						if(null!=list && list.size()>0){
							if(list.size()<Constant.LIST_PAGE_COUNT){
								pullToRefreshGridView.setMode(Mode.PULL_FROM_START);
							}else{
								pullToRefreshGridView.setMode(Mode.BOTH);
							}
							sortLayout.setVisibility(View.VISIBLE);
							if(isDown){
								listProductModel.clear();
							}
							listProductModel.addAll(list);
							adatper.setCurrencyCode(null, list.get(0).getCurrencyCodeSymbol());
							adatper.notifyDataSetChanged();
						}else{
							sortLayout.setVisibility(View.GONE);
							showEmptyLayout(pullToRefreshGridView,R.string.no_products_suggest,R.drawable.sorry);
						}
					}else{
						sortLayout.setVisibility(View.GONE);
						if(listProductModel.size()>0){
							AlertToast.alert(SpecialActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
							--pageIndex;
						}else{
							showErrorLayout(result, pullToRefreshGridView);
						}
					}
				}
				
			}
		}));
	}
	
	/**
	 * 获取广告banner的商品列表
	 * 
	 * @author hjd008
	 * @version [版本号, 2014-12-24]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	private class GetBannerProductListAsyncTask extends
			AsyncTask<Void, Void, String> {
		SearchModel searchModel = null;
		@Override
		protected void onPreExecute() {
			//showWaitingDialog();
			loadingLayout.setVisibility(View.VISIBLE);
			sortLayout.setSortBtnEnable(false);
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				String currencyCode = StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE, getString(R.string.currency_default_currencyCode));
				searchModel = adPromotionServiceProvider
						.getBannerProductsWhere(bannerModel.getBannerID(), 1,
								100, sortLayout.getCurrentSortType(), 0, Double.MAX_VALUE, 0.00,currencyCode,
								ActivityUtil.getCustomerID(),OnekeyFilterLocalUtil.getFilterState(SpecialActivity.this),
								OnekeyFilterLocalUtil.getLocalCategoryIds(SpecialActivity.this));
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			if(!isFinishing()){
				//hideWaitingDialog();
				loadingLayout.setVisibility(View.GONE);
				sortLayout.setSortBtnEnable(true);
				if (TextUtils.equals("0", result)) {
					hideAllLayout(pullToRefreshGridView);
					sortLayout.setVisibility(View.VISIBLE);
					listProductModel = (ArrayList<ProductModel>) searchModel.getProductModels();
					if (null != listProductModel && !listProductModel.isEmpty()) {
						// 填充搜索列表视图
//						adatper = new SpecialAdapter(SpecialActivity.this,
//								listProductModel,densityDpi,tracker);
						adatper = new ProductListAdapter(SpecialActivity.this,
								listProductModel, false, densityDpi,tracker);
						if(searchModel!=null){
							//设置显示Currency
							adatper.setCurrencyCode(searchModel.getCurrencyCode(), searchModel.getCurrencyCodeSymbol());
						}
						pullToRefreshGridView.setAdapter(adatper);

						pullToRefreshGridView.requestFocus();
					}else{
						sortLayout.setVisibility(View.GONE);
						showEmptyLayout(pullToRefreshGridView, R.string.no_products_suggest,
								R.drawable.sorry);
					}
				} else {
					// 加载第一页因网络未连接或者超时显示网络异常页面
					/*if (TextUtils.equals(
							ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE,
							result)
					
					 * || TextUtils.equals(ServerConstant.ReturnCode.
					 * VALIDATOR_CONNECT_TIMEOUT, result)
					 ) */{
						 sortLayout.setVisibility(View.GONE);
						 if(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)){
							 showErrorLayout(pullToRefreshGridView, R.string.internet_error, R.string.internet_suggest, R.drawable.no_internet);
						 }else{
							 showErrorLayout(pullToRefreshGridView, R.string.server_busy, R.string.server_suggest, R.drawable.no_internet);
						 }
						retryBtn.setOnClickListener(
								new OnClickListener() {
									@Override
									public void onClick(View v) {
										// new
										// GetBannerProductListAsyncTask().execute();
										excuteTask(false);
									}
								});
					} /*else {
						AlertToast.alert(SpecialActivity.this,
								ServerConstant.ReturnCode.MESSAGEMAP.get(result));
					}*/
				}
			}
			super.onPostExecute(result);
		}

	}

	private void initView() {
		 densityDpi=getDensityDpi();
		sortLayout = (SortView) findViewById(R.id.banner_sort_layout);
		sortLayout.setPopularityStr(Constant.SORT_POPULARITY);
		sortLayout.setDefaultSortStyle();
		sortLayout.setOnSortViewItemClickListenner(this);
		loadingLayout = (LinearLayout)findViewById(R.id.loading_layout);
		pullToRefreshGridView = (PullToRefreshGridView) findViewById(R.id.data_list);
		toTop = (ImageButton) findViewById(R.id.special_totop);
		invalidActiveLayout = (RelativeLayout) findViewById(R.id.layout_invalid_active);


		filterModelLayout = (RelativeLayout) findViewById(R.id.on_filter_model_layout);
		String config;
		if(ActivityUtil.isLogin(SpecialActivity.this)){
			config = StringUtil.getConfig(ActivityUtil.getCustomerID()+ServerConstant.OneKeyFilter.ISFILTERKEY_ONLINE, "false");
		}else{
			config = StringUtil.getConfig(ServerConstant.OneKeyFilter.ISFILTERKEY_LOCAL, "false");
		}
		filterModelLayout.setVisibility("true".equals(config)?View.VISIBLE:View.GONE);
		findViewById(R.id.on_filter_model_layout_delete).setOnClickListener(this);
		
		setLeftBtnContent(true, -1);
			toTop.setOnClickListener(this);
			pullToRefreshGridView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true){
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					if(view.getFirstVisiblePosition()>4){
						toTop.setVisibility(View.VISIBLE);
					}else{
						toTop.setVisibility(View.GONE);
					}
					super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
				}
				
			});  
//		setRightBtnContent(R.string.share)
//			setRightBtnBitmap().setOnClickListener(
//				new OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						new AlertDialog.Builder(SpecialActivity.this)
//								.setTitle(
//										getResources()
//												.getString(R.string.share))
//								.setPositiveButton(
//										getResources().getString(
//												R.string.Shareto),
//										new DialogInterface.OnClickListener() {
//
//											@Override
//											public void onClick(
//													DialogInterface dialog,
//													int which) {
//												Intent emailIntent = new Intent(
//														android.content.Intent.ACTION_SEND);
//												emailIntent
//														.setType("text/html");
//												emailIntent
//														.putExtra(
//																android.content.Intent.EXTRA_SUBJECT,
//																R.string.desc);
//												emailIntent
//														.putExtra(
//																android.content.Intent.EXTRA_TEXT,
//																"http://www.dealextreme.com/");
//												startActivity(Intent
//														.createChooser(
//																emailIntent,
//																"sendEmail......"));
//											}
//										})
//								.setNegativeButton("Cancel",
//										new DialogInterface.OnClickListener() {
//
//											@Override
//											public void onClick(
//													DialogInterface dialog,
//													int which) {
//												dialog.dismiss();
//											}
//										}).create().show();
//					}
//				});
			
			//返回按钮的事件
			topbarLeftTv.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(isFromMessage){
						backToHome();
					}else{
						finish();
					}
				}
			});

	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.special_totop://返回列表顶部
			adatper.notifyDataSetInvalidated();
			return;
		case R.id.on_filter_model_layout_delete:// 隐藏过滤模式提示信息
			filterModelLayout.setVisibility(View.GONE);
			break;
		default:
			break;
		}
		
	}
	
	@Override
	public void onPopulayityClick() {
		if(null!=listProductModel){
			listProductModel.clear();
		}
		excuteTask(false);
	}

	@Override
	public void onPriceClick() {
		if(null!=listProductModel){
			listProductModel.clear();
		}
		excuteTask(false);		
	}

	@Override
	public void onDisCountClick() {
		if(null!=listProductModel){
			listProductModel.clear();
		}
		excuteTask(false);		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(isFromMessage){
				backToHome();
			}else{
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
